package com.beta.cat.application;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.nacos.api.naming.NamingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.registry.dubbo.DubboRegistryFactory;
import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.context.ApplicationContext;

import javax.annotation.PostConstruct;

@Slf4j
@Aspect
@EnableDiscoveryClient //开启服务注册与发现功能
public class DubboBaseApplication extends BaseApplication {
    @Autowired
    private ApplicationContext ctx;

    @PostConstruct
    public void init() {

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                super.run();
                log.info("DubboBaseApplication.shutdownHook start");
                try {
                    NacosServiceManager nacosServiceManagerStatic = ctx.getBean(NacosServiceManager.class);
                    NacosDiscoveryProperties nacosDiscoveryPropertiesStatic = ctx.getBean(NacosDiscoveryProperties.class);
                    //将服务从注册中心下线
                    NamingService namingService = nacosServiceManagerStatic.getNamingService(nacosDiscoveryPropertiesStatic.getNacosProperties());
                    namingService.deregisterInstance(nacosDiscoveryPropertiesStatic.getService(), nacosDiscoveryPropertiesStatic.getIp(), nacosDiscoveryPropertiesStatic.getPort());

                    //将 Dubbo 服务销毁
                    DubboRegistryFactory.destroyAll();
                    DubboProtocol.getDubboProtocol().destroy();
                } catch (Throwable e) {
                    e.printStackTrace();
                }
                log.info("DubboBaseApplication.shutdownHook end");
            }
        });
    }

    @Before("execution(* org.springframework.cloud.client.serviceregistry.ServiceRegistry.register(*)) && args(registration)")
    public void beforeRegister(Registration registration) {
        log.info("DubboBaseApplication.beforeRegister");
        DubboBootstrap dubboBootstrap = DubboBootstrap.getInstance();
        dubboBootstrap.start();
    }
}